﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;

namespace Serviio.API
{
    internal static class RESTHelper
    {
        internal static XmlDocument Get(string URL)
        {
            try
            {
                HttpWebRequest req = HttpWebRequest.Create(URL) as HttpWebRequest;
                req.Method = "GET";
                req.ContentLength = 0;
                req.Timeout = 10000;
                using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
                {
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(resp.GetResponseStream());
                    return xDoc;
                }
            }
            catch
            {
                return null;
            }
        }

        internal static bool Put(string URL, XmlDocument xDoc)
        {
            return SendXmlDoc("PUT", URL, xDoc);
        }

        internal static bool Post(string URL, XmlDocument xDoc)
        {
            return SendXmlDoc("POST", URL, xDoc);
        }

        private static bool SendXmlDoc(string Method, string URL, XmlDocument xDoc)
        {
            try
            {
                HttpWebRequest req = HttpWebRequest.Create(URL) as HttpWebRequest;
                req.Method = Method;
                req.ContentType = "text/xml";
                req.Timeout = 10000;
                req.ReadWriteTimeout = 1000;

                using (MemoryStream str = new MemoryStream())
                {
                    xDoc.Save(str);
                    req.ContentLength = str.Length;
                }

                xDoc.Save(req.GetRequestStream());

                using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
                {
                    if (resp == null || resp.StatusCode != HttpStatusCode.OK)
                        return false;

                    xDoc = new XmlDocument();
                    xDoc.Load(resp.GetResponseStream());

                    string status = xDoc.SelectSingleNode("/result/errorCode").InnerText;
                    if (!"0".Equals(status))
                        return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

    }
}
